import Vue from 'vue'
import Router from 'vue-router'
import login from '@/views/_login'
import home from '@/views/_home'
import not_found from '@/views/404'
import shop from '@/views/nav/_shop'
import auth from '@/views/nav/_auth'
import list from '@/views/nav/_list'
import {
  store
} from '@/vuex/store'

Vue.use(Router)


const router = new Router({
  mode: 'history',
  strict: process.env.NODE_ENV !== 'production',
  routes: [{
      path: '*',
      redirect: {
        path: '/404'
      }
    }, {
      path: '/',
      name: 'login',
      component: login
    }, {
      path: '/404',
      component: not_found,
      name: ''
    },
    {
      hidden: true,
      path: '/',
      component: home,
      name: 'main',
      children: [{
        path: '/auth',
        component: auth,
        name: '商家认证',
        icon: 'el-icon-star-off'
      }, {
        path: '/shop',
        component: shop,
        name: '店鋪管理',
        icon: 'el-icon-location'
      }, {
        path: '/list',
        component: list,
        name: '预约清单',
        icon: 'el-icon-tickets'
      }]
    },
  ]
})

// 全局路由守卫
router.beforeEach((to, from, next) => {
  // to: Route: 即将要进入的目标 路由对象
  // from: Route: 当前导航正要离开的路由
  // next: Function: 一定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数。

  const nextRoute = ['店鋪管理', '商家认证', '预约清单'];
  let isLogin = store.state.isLogin; //global.isLogin;  // 是否登录
  // 未登录状态；当路由到nextRoute指定页时，跳转至login
  if (nextRoute.indexOf(to.name) >= 0) {
    if (isLogin === 0) {
      console.info('what fuck');
      router.push({
        path: '/'
      })
      return;
    }
  }
  // 已登录状态；当路由到login时，跳转至home 
  if (to.name === 'login') {
    if (isLogin) {
      router.push({
        path: '/shop'
      });
    }
  }
  next();
});

export default router;
